import Taro from "@tarojs/taro";
import { ref } from "vue";

import { carsQuery, listByTruckName, carsQueryById, saveSelfCar } from "../api";
export const useSearchCar = ({ state, dicMap, route, EventChannel }) => {
  const carList = ref([]);
  const showMore = ref(false);
  const searchValue = ref("");
  const showSearch = ref(false);

  //默认查询车辆
  const initCarList = () => {
    const queryParams = {};
    // 有柜空车捆绑
    if (state.truckPayloadType.isHasBoxEmptyCar) {
      queryParams.truckType = 1;
      if (dicMap.userType.isOperator) {
        queryParams.param = 2;
      }
    }
    carsQuery(queryParams).then((res) => {
      carList.value = (
        res.data?.recordList?.filter((item) => {
          item.id = item.truckId;
          return !!item.truckLicenseName;
        }) || []
      ).splice(0, 9);
      showSearch.value = carList.value.length > 8;

      if (route.query.carInfo) {
        /**
         * 有带过来车辆数据，因为 truckId 可能存在不相等的情况
         * 这里用车牌号匹配对应的 id
         */
        const carInfo = JSON.parse(route.query.carInfo);
        const truckLicenseName = carInfo.truckLicenseName;
        const matchCarInfo = carList.value.filter(
          (item) => item.truckLicenseName === truckLicenseName
        );
        if (matchCarInfo.length && matchCarInfo[0].id) {
          state.carForm.id = matchCarInfo[0].id;
        }
      }
    });
  };
  initCarList();

  //清空
  const handleClear = () => {
    initCarList();
  };

  //根据关键字查询车辆
  const searchCarList = () => {
    const data = {
      param: searchValue.value,
    };
    if (state.truckPayloadType.isHasBoxEmptyCar) {
      // 有柜空车只查询货柜车 1 货柜车  0 吨车
      data.truckType = "1";
    }
    listByTruckName(data).then((res) => {
      carList.value = res.data || [];
      if (carList.value.length === 0) {
        Taro.showToast({
          title: "未查询到车辆，请先维护",
          icon: "none",
          duration: 2000,
        });
      }
    });
  };

  // 车辆数据处理
  // const handleCarInfo = (carInfo, isEdit) => {
  const handleCarInfo = (carInfo, from) => {
    state.carForm.data = carInfo;
    if (!state.carForm.data.rountingCountryCode) {
      state.carForm.data.rountingCountryCode = "HK";
    }

    // 有柜空车捆绑默认只有货柜车并选中
    if (state.truckPayloadType.isHasBoxEmptyCar) {
      state.carForm.data.truckType = "1";
    }

    if (!state.carForm.data.numStaffMember) {
      state.carForm.data.numStaffMember = 1;
    }
    if (!state.carForm.data.belongName) {
      state.carForm.data.belongName = "";
    }
    // 处理车辆的集装箱数据
    if (state.carForm.data?.boxing?.length === 1) {
      /**
       * NOTE: 业务需求
       * 默认不带封志信息，将封志信息缓存起来
       * 存在封装信息时，集装箱表单页面展示调取选择框
       * 勾选调取，自动填充缓存的封志信息
       */
      // 处理封志信息（旧版是把封志信息存在本地缓存）
      const {
        boxingSealed,
        boxingSealedName,
        boxingSealedType,
      } = state.carForm.data.boxing[0];
      // 有维护封志信息才保存到缓存中，否则清空缓存的封志信息
      if (boxingSealed || boxingSealedName || boxingSealedType) {
        state.carForm.data.cacheSealedInfo = {
          boxingSealed,
          boxingSealedName,
          boxingSealedType,
        };
        // 非编辑已选车辆情况下，清除封志信息字段，否则会展示和自动填充表单
        if (from === "isNew") {
          delete state.carForm.data.boxing[0].boxingSealed;
          delete state.carForm.data.boxing[0].boxingSealedName;
          delete state.carForm.data.boxing[0].boxingSealedType;
        }
      }
      // 不存在 boxingCode 删除车辆数据中集装箱数据
      if (from === "isNew" && !state.carForm.data.boxing[0].boxingCode) {
        delete state.carForm.data.boxing;
      }
    }

    const driverList = carInfo.driverList;
    if (driverList?.length === 1) {
      // 车辆绑定一个司机
      Object(state.carForm.data, {
        driverName: driverList[0].driverName,
        driverCode: driverList[0].driverCode,
        dMobile: driverList[0].dMobile,
      });
      // 网页端司机信息基础数据增加了健康状态和有预防接种录入项维护
      if (driverList[0]?.healthStatus === 0) {
        state.carForm.data.healthStatus = driverList[0].healthStatus;
      } else {
        state.carForm.data.healthStatus = 1;
      }
      if (driverList[0].vaccinate) {
        state.carForm.data.vaccinate = driverList[0].vaccinate;
      } else {
        state.carForm.data.vaccinate = 0;
      }
      // 清空 selectDrivers，否则在切换选中车辆的时候还存在旧数据
      state.selectDrivers = [];
    } else if (driverList?.length > 1) {
      //多个司机
      state.selectDrivers = driverList.reduce(
        (prev, item) => {
          prev.push({
            para_value: item.driverCode,
            para_name: item.driverName,
            ...item,
          });
          return prev;
        },
        [{ para_value: "", para_name: "--请选择--" }]
      );
      // 多个司机且不为编辑状态时，司乘人员默认规则按原来的默认值 健康状态为1 疫苗情况为0
      if (from === "isEdit") {
        // 编辑状态
        if (carInfo.healthStatus === "0" || carInfo.healthStatus === 0) {
          state.carForm.data.healthStatus = 0;
        } else {
          state.carForm.data.healthStatus = 1;
        }
        state.carForm.data.vaccinate = +carInfo.vaccinate || 0;
      } else {
        state.carForm.data.healthStatus = 1;
        state.carForm.data.vaccinate = 0;
      }

      // 新选择车辆 默认为 请选择
      from !== "isEdit" && (state.carForm.data.driverName = "");
    } else {
      //未绑定司机

      // 清空 selectDrivers，否则在切换选中车辆的时候还存在旧数据
      state.selectDrivers = [];

      const { healthStatus, vaccinate } = state.carForm.data;
      state.carForm.data.healthStatus = healthStatus?.toString()
        ? +healthStatus
        : 1;
      state.carForm.data.vaccinate = vaccinate?.toString() ? +vaccinate : 0;
    }
    // 个人版用原有的默认规则 与else重复
    // if (dicMap.userType.isPersonal) {
    //   state.carForm.data.healthStatus = 1;
    //   state.carForm.data.vaccinate = 0;
    // }
    state.carForm.show = true;
  };

  // 主页已选车辆
  if (route.query.carInfo) {
    handleCarInfo(JSON.parse(route.query.carInfo), "isEdit");
  }

  //根据id获取车辆信息
  const editCar = (id) => {
    state.carForm.id = id;
    carsQueryById({
      param: id,
    }).then((res) => {
      /**
       * 如果路由带有车辆数据的情况下点选车辆
       * 车辆基础数据中如果有封志信息，则更新封志信息，
       * 没有则保留原来的封志信息
       */
      const queryCarData = res.data[0];
      if (!queryCarData?.boxing && state.carForm.data?.boxing) {
        queryCarData.boxing = state.carForm.data.boxing;
      }
      handleCarInfo(queryCarData, "isNew");
    });
  };

  return () => (
    <tz-view class="search-area">
      {showSearch.value && (
        <>
          {!showMore.value && (
            <tz-view onClick={() => (showMore.value = !showMore.value)}>
              查看更多
            </tz-view>
          )}
          {showMore.value && (
            <tz-view class="search-content">
              <tz-search
                prefix-icon="search"
                v-model={searchValue.value}
                placeholder="输入车牌查询"
                clearable
                round
                showAction
                type="text"
                onClear={handleClear}
                onSearch={searchValue.value ? searchCarList : initCarList}
              ></tz-search>
            </tz-view>
          )}
        </>
      )}

      <tz-view class="car-list">
        {carList.value.map((item) => (
          <tz-button
            size="small"
            key={item.id}
            round
            type={item.id === state.carForm.id ? "primary" : "default"}
            class={{ "bg-white": item.id !== state.carForm.id }}
            onClick={() => editCar(item.id)}
          >
            {item.truckLicenseName}
          </tz-button>
        ))}
      </tz-view>
    </tz-view>
  );
};

export const useEditCar = ({ state, dicMap, navigateBack }) => {
  state.countryIndex = 0;
  const handleCancel = () => {
    navigateBack();
  };
  const handleSave = () => {
    const formData = state.carForm.data;
    if (!checkFormData(formData)) {
      return;
    }
    //1596.车牌录入繁体“粵”，自动转换为简体“粤”​
    formData.truckLicenseName = formData.truckLicenseName.replace("粵", "粤");
    //保存车辆信息
    saveSelfCar(formData).then(async (res) => {
      navigateBack({
        delta: state.type === "add" ? 2 : 1, // 新增车辆直接返回到主页
        event: {
          type: "truckHomeBack", //事件类型 ，可以自己任意定义
          data: formData, //回退的数据
        },
      });
    });
  };
  /**
   * 车牌验证
   */
  function isTruckLicense(str) {
    //如果以粤A或粤Z开头则中间4位数字或字母尾部加上一个港或澳字,如果以粤福开头则以4个数字结尾,如果是粤B则以5位字母或数字结尾
    const patrn1 = /^[粤|粵]{1}[A|Z|a|z]{1}.*$/; //以粤A|Z开头
    const patrn2 = /^[粤|粵]{1}[福]{1}.*$/; //以粤福开头
    const patrn3 = /^[粤|粵]{1}[B|b]{1}.*$/; //以粤B开头
    if (patrn1.exec(str)) {
      //以粤A|Z开头
      const patrn11 = /^[粤|粵]{1}[A|Z|a|z]{1}[A-Za-z0-9]{4}[港澳]{1}$/;
      if (patrn11.exec(str)) {
        //如果以粤A或粤Z开头则中间4位数字或字母尾部加上一个港或澳字
        return 0;
      } else {
        return 1;
      }
    } else if (patrn2.exec(str)) {
      //以粤福开头
      const patrn22 = /^[粤|粵]{1}[福]{1}[0-9]{4}$/;
      if (patrn22.exec(str)) {
        //以粤福开头则以4个数字结尾
        return 0;
      } else {
        return 2;
      }
    } else if (patrn3.exec(str)) {
      //以粤B开头
      const patrn33 = /^[粤|粵]{1}[B|b]{1}[A-Za-z0-9]{5}$/;
      if (patrn33.exec(str)) {
        //以粤B开头则以5位字母或数字结尾
        return 0;
      } else {
        return 3;
      }
    } else {
      return 4;
    }
  }
  /**
   * 是否为空字符串
   */
  function isEmpty(str) {
    return (
      str === null || str === undefined || str.trim() === "" || str === "null"
    );
  }
  /**
   * 验证手机号
   */
  function isMobile(str) {
    const patrn = /^\d{1}[\d,-]{3,}\d{1}$/;
    return !patrn.exec(str);
  }
  /**
   * 字符实际长度校验
   */

  function isLength(str, num) {
    //先把中文替换成两个字节的英文，在计算长度
    return str.replace(/[\u0391-\uFFE5]/g, "aa").length > num;
  }
  /**
   * 车辆编码  司机卡号
   */
  function iscode(str) {
    const patrn = /^[A-Z0-9]{8,10}$/;
    if (patrn.exec(str)) {
      return false;
    } else {
      return true;
    }
  }
  /**
   * 司机卡号
   */
  function isDriverCode(str) {
    const patrn = /^[A-Z0-9]{6,18}$/;
    if (!iscode(str) || patrn.exec(str)) {
      return false;
    } else {
      return true;
    }
  }
  /**
   * 校验表单数据
   */
  const checkFormData = (formData) => {
    // 内地车牌
    if (isEmpty(formData.truckLicenseName)) {
      $TzNotify.danger("请输入内地车牌");
      return false;
    }
    //如果以粤A或粤Z开头则中间4位数字或字母尾部加上一个港或澳字,如果以粤福开头则以4个数字结尾,如果是粤B则以5位字母或数字结尾
    if (isTruckLicense(formData.truckLicenseName) === 4) {
      const errMsg =
        "1.粤|粵A,Z开头中间4位大写字母或数字 后面带‘港’或者‘澳’\n2.粤|粵福开头接4位数字 \n3.粤|粵B开头接5位大写字母或数字";
      $TzNotify.danger(errMsg);
      return false;
    }
    if (isTruckLicense(formData.truckLicenseName) === 1) {
      $TzNotify.danger("请输入内地车牌 格式如: 粤|粵Z****港/澳");
      return false;
    }
    if (isTruckLicense(formData.truckLicenseName) === 2) {
      $TzNotify.danger("请输入内地车牌 格式如: 粤|粵福1234");
      return false;
    }
    if (isTruckLicense(formData.truckLicenseName) === 3) {
      $TzNotify.danger("请输入内地车牌 格式如: 粤|粵B12345/粤|粵B123AB");
      return false;
    }

    // 海关代码
    if (isEmpty(formData.truckLicenseCode)) {
      $TzNotify.danger("请输入车辆海关代码");
      return false;
    }
    if (iscode(formData.truckLicenseCode)) {
      $TzNotify.danger("车辆海关代码只能输入8至10位大写字母或数字");
      return false;
    }
    // 车辆类型
    if (isEmpty(formData.truckType)) {
      $TzNotify.danger("请输入车辆类型");
      return false;
    }
    // 司机姓名
    if (isEmpty(formData.driverName)) {
      $TzNotify.danger("请输入司机姓名");
      return false;
    }
    if (isLength(formData.driverName, 10)) {
      $TzNotify.danger("司机姓名只能输入10位字符（中文占俩个字符）");
      return false;
    }
    // 司机卡号
    if (isEmpty(formData.driverCode)) {
      $TzNotify.danger("请输入司机卡号");
      return false;
    }
    if (isDriverCode(formData.driverCode)) {
      $TzNotify.danger("司机卡号只能输入6至18位大写字母或数字");
      return false;
    }

    if (
      dicMap.userType.isPersonal &&
      !isEmpty(formData.dMobile) &&
      isMobile(formData.dMobile)
    ) {
      $TzNotify.danger("司机联系方式格式有误! 例:13618181818,0755-2156245");
      return false;
    }

    if (
      dicMap.userType.isPersonal &&
      !isEmpty(formData.dMobile) &&
      formData.dMobile.indexOf(",") > -1
    ) {
      $TzNotify.danger("司机联系方式只能输入一个");
      return false;
    }

    if (!formData.healthStatus && formData.healthStatus !== 0) {
      $TzNotify.danger("请选择健康状态");
      return false;
    }

    if (!formData.vaccinate && formData.vaccinate !== 0) {
      $TzNotify.danger("请选择有效预防接种");
      return false;
    }

    return true;
  };

  const truckTypeOption = [{ text: "货柜车", value: "1" }];
  // 有柜空车捆绑默认只有货柜车并选中
  if (!state.truckPayloadType.isHasBoxEmptyCar) {
    truckTypeOption.push({ text: "吨车", value: "0" });
  }

  return () => (
    <>
      <tz-view class="form-content border-t1">
        <tz-cell title="内地车牌" border>
          <tz-input
            v-model={state.carForm.data.truckLicenseName}
            disabled={state.isDisabled}
            type="text"
            placeholder="请输入内地车牌"
            rules={(val) => {
              let value = val?.match(/[\u4e00-\u9fa5\w]{0,7}/g)?.[0];
              // 把繁体的粤改成简体
              if (value && value[0] === "粵") {
                value = value.replace("粵", "粤");
              }
              return value.toUpperCase();
            }}
          />
        </tz-cell>
        <tz-cell title="车辆海关编码" border>
          <tz-input
            v-model={state.carForm.data.truckLicenseCode}
            disabled={state.isDisabled}
            type="text"
            placeholder="请输入黄本编号"
            maxlength="10"
          />
        </tz-cell>
        <tz-cell title="车辆类型" border>
          <tz-radio-group
            v-model={state.carForm.data.truckType}
            disabled={state.isDisabled}
            options={truckTypeOption}
          ></tz-radio-group>
        </tz-cell>
        <tz-cell title="司机姓名" border>
          {!!state?.selectDrivers?.length && (
            <tz-picker
              mode="selector"
              v-model={state.carForm.data.driverName}
              range={state.selectDrivers}
              rangeKey="para_name"
              onChange={(e, item) => {
                state.carForm.data.driverCode = item.driverCode;
                state.carForm.data.dMobile = item.dMobile;
                // 网页端司机信息基础数据增加了健康状态和有预防接种录入项维护
                state.carForm.data.healthStatus =
                  item.healthStatus === 0 ? 0 : 1;
                state.carForm.data.vaccinate = item.vaccinate || 0;
              }}
            ></tz-picker>
          )}
          {!state?.selectDrivers?.length && (
            <tz-input
              v-model={state.carForm.data.driverName}
              disabled={state.isDisabled}
              type="text"
              placeholder="请输入司机姓名"
            />
          )}
        </tz-cell>
        <tz-cell title="司机卡号" border>
          <tz-input
            v-model={state.carForm.data.driverCode}
            disabled={state.isDisabled}
            type="text"
            placeholder="请输入司机卡备案号"
            maxlength="18"
          />
        </tz-cell>
        <tz-cell title="司机联系方式" border>
          <tz-input
            v-model={state.carForm.data.dMobile}
            disabled={state.isDisabled}
            type="text"
            placeholder="请输入短信通知手机"
          />
        </tz-cell>
        {!dicMap.userType.isPersonal && (
          <tz-cell title="车辆牌头公司" border>
            <tz-input
              v-model={state.carForm.data.belongName}
              type="text"
              disabled
            />
          </tz-cell>
        )}
        <tz-cell title="司乘人员数" border>
          <tz-input
            v-model={state.carForm.data.numStaffMember}
            type="number"
            maxlength="1"
            placeholder="请输入司乘人员数"
          />
        </tz-cell>
        <tz-cell title="健康状态" border>
          <tz-radio-group
            v-model={state.carForm.data.healthStatus}
            options={[
              { text: "正常", value: 1 },
              { text: "异常", value: 0 },
            ]}
          ></tz-radio-group>
        </tz-cell>
        <tz-cell title="有预防接种" border>
          <tz-radio-group
            v-model={state.carForm.data.vaccinate}
            options={[
              { text: "是", value: 1 },
              { text: "否", value: 0 },
            ]}
          ></tz-radio-group>
        </tz-cell>
        <tz-cell title="途径国家(地区)" border>
          <tz-picker
            mode="selector"
            v-model={state.carForm.data.rountingCountryCode}
            range={dicMap.countryCodeList}
            rangeKey="para_name"
            valueKey="para_value"
          ></tz-picker>
        </tz-cell>
      </tz-view>
      <tz-view class="btn-content">
        <tz-button onClick={handleCancel}>取消</tz-button>
        <tz-button type="primary" onClick={handleSave}>
          确定
        </tz-button>
      </tz-view>
    </>
  );
};
